from datetime import datetime, timedelta
import requests
from enum import Enum

# 定义时间范围枚举类
class TimeWindow(Enum):
    HOUR = 2 #按小时聚合
    DAY = 1 #按天聚合


def get_previous_week_range(current_date: (datetime | str) = None) -> (str,str):
    """
    获取上一周的起始和结束日期（周一 00:00:00 到周日 23:59:59）

    参数:
        current_date (datetime|str): 可选，基准日期，默认为当前日期。可以是datetime对象或"YYYY-MM-DD"格式字符串

    返回:
        tuple: (start_date_str, end_date_str) 格式为"YYYY-MM-DD HH:MM:SS"的字符串元组

    示例:
        >>> get_previous_week_range("2025-07-15")
        ('2025-07-07 00:00:00', '2025-07-13 23:59:59')
    """
    # 处理输入日期
    if current_date is None:
        today = datetime.now()
    elif isinstance(current_date, str):
        today = datetime.strptime(current_date, "%Y-%m-%d")
    else:
        today = current_date

    # 计算本周一
    this_monday = today - timedelta(days=today.weekday())

    # 计算上周日（上周的最后一天）
    last_sunday = this_monday - timedelta(days=1)

    # 计算上周一（上周的第一天）
    last_monday = last_sunday - timedelta(days=6)

    # 格式化为字符串
    start_date = last_monday.replace(hour=0, minute=0, second=0)
    end_date = last_sunday.replace(hour=23, minute=59, second=59)

    return (
        start_date.strftime("%Y-%m-%d %H:%M:%S"),
        end_date.strftime("%Y-%m-%d %H:%M:%S")
    )


def get_max_version_data(
        start_date_str: str,
        end_date_str: str,
        product_id: str,
        time_window: TimeWindow = TimeWindow.DAY,
) -> str:
    """
    获取Bugly数据中版本分布的最大版本号

    参数:
        start_date_str (str): 开始日期，格式"YYYY-MM-DD HH:MM:SS"
        end_date_str (str): 结束日期，格式"YYYY-MM-DD HH:MM:SS"
        product_id (str): 产品ID
        time_window (TimeWindow): 时间窗口类型(2小时聚合,1天聚合)

    返回:
        dict: 包含最大版本号和文档数的字典 {'version': str, 'count': int}
    """
    # 验证日期格式并转换为时间戳
    try:
        start_dt = datetime.strptime(start_date_str, "%Y-%m-%d %H:%M:%S")
        end_dt = datetime.strptime(end_date_str, "%Y-%m-%d %H:%M:%S")
        start_ts = str(int(start_dt.timestamp()))
        end_ts = str(int(end_dt.timestamp()))
    except ValueError:
        raise ValueError("日期格式必须为'YYYY-MM-DD HH:MM:SS'")

    headers = {
        'Authorization': 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NTYwMTQxNDkuNjIyMTA4LCJpYXQiOjE3NTM0MjIxNDkuNjIyMTA4LCJpc3MiOiJ0ZW5jZW50IiwiY3VzdG9tIjp7InVpbiI6IjMwODU1NTMyMzE2NzI5OTMiLCJzVG9rZW4iOiJmMTE0MmYzOTVjMTMyZTNlODQ5YWU2ZGI3YTRhZmE0OCIsImNpZCI6IjdjYTRiMzI0NmFhZTQ5OTEzY2M0NjE3ZTczOGZhYWNjIn19.gD91itZ1MEJ2gh1ykm7SMen1pRAg0Wxw7r2U7JTSJ8tKYT9rYq61VoV4nskNPY4H0VFfwZYYEWqzGQISTqL8vQ',
        'X-ProductID': product_id,
    }

    # 构造POST请求数据
    json_data_post = {
        'form_list': {
            'time_window': time_window.value,
            'filters': [
                {
                    'name': 'event_time',
                    'values': [start_ts],
                    'operator': 'GE',
                },
                {
                    'name': 'event_time',
                    'values': [end_ts],
                    'operator': 'LE',
                },
            ],
        },
    }

    # 获取token
    token_response = requests.post(
        'https://bugly.tds.qq.com/v5/api/url-token/get',
        headers=headers,
        json=json_data_post
    )
    token = token_response.json()['token']

    # 构造GET请求数据（固定部分）
    json_data_get = {
        'productId': product_id,
        'token': token,
        'type': 2,
        'subTypes': [14, 16],  # 固定值
        'sortField': 'doc_count',
        'sortType': 'DESC',
        'page': 1,
        'pageSize': 10,
        'dimensions': ['app_version'],  # 固定维度
    }

    # 获取数据
    data_response = requests.post(
        'https://bugly.tds.qq.com/v5/trpc/trpc.rmonitor.metrics_server.GetMetrics/GetDimensionList',
        headers=headers,
        json=json_data_get,
    )

    # 提取最大版本号数据
    if data_response.json().get('data'):
        first_item = data_response.json()['data'][0]
        # return {
        #     'version': first_item['dimension'][0],
        #     'count': first_item['docCount']
        # }
        return first_item['dimension'][0]
    else:
        raise ValueError("未获取到有效数据，响应: " + str(data_response.json()))

    # 使用示例
if __name__ == "__main__":
    # # 示例1：获取上周范围（基于当前日期）
    # last_week_start, last_week_end = get_previous_week_range()
    # print(f"上周范围（自动计算）: {last_week_start} 到 {last_week_end}")
    #
    # # 示例2：获取指定日期的上周范围
    # test_date = "2025-07-15"  # 2025年7月15日是周二
    # custom_start, custom_end = get_previous_week_range(test_date)
    # print(f"2025-07-15的上周范围: {custom_start} 到 {custom_end}")
    #
    # # 示例3：结合Bugly接口使用
    # start, end = get_previous_week_range()
    # print(f"\n可用于Bugly接口的参数:")
    # print(f"start_date_str='{start}'")
    # print(f"end_date_str='{end}'")

    try:
        result = get_max_version_data(
            start_date_str="2025-07-03 00:00:00",
            end_date_str="2025-07-06 23:59:59",
            product_id="b99545917b",
            time_window=TimeWindow.DAY
        )
        # print(f"最大版本号: {result['version']}, 出现次数: {result['count']}")
        print(f"最大版本号:{result}")

    except Exception as e:
        print(f"发生错误: {str(e)}")